/**
 * This file is released under the GNU General Public License.
 * Refer to the COPYING file distributed with this package.
 *
 * Copyright (c) 2008-2009 WURFL-Pro srl
 */
package net.sourceforge.wurfl.core.handlers.classifiers;

import java.util.HashSet;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;

import org.apache.commons.collections.set.UnmodifiableSet;
import org.apache.commons.collections.set.UnmodifiableSortedSet;
import org.apache.commons.lang.Validate;
import org.apache.commons.lang.builder.ToStringBuilder;

import edu.emory.mathcs.backport.java.util.concurrent.ConcurrentSkipListMap;

/**
 * Filtered device data.
 * 
 * <p>
 * This class is responsible for collect devices classified according to their
 * user-agent.
 * </p>
 * 
 * @author WURFL-PRO SRL, Rome, Italy
 * @version $Id: FilteredDevices.java 1116 2009-03-20 10:01:40Z filippo.deluca $
 */
public class FilteredDevices {

	/** The map of user-agent and device identifier. */
	private SortedMap/*String,String*/ data = new ConcurrentSkipListMap();

	/** Default constructor */
	public FilteredDevices() {
		// Empty
	}

	/**
	 * Return the collected user-agent <b>naturally ordered</b>.
	 * 
	 * @return A {@link SortedSet} containing collected user-agent.
	 */
	public SortedSet getUserAgents() {
		return UnmodifiableSortedSet.decorate((SortedSet) data.keySet());
	}

	/**
	 * Return the collected user-agent <b>naturally ordered</b>.
	 * 
	 * @return A {@link SortedSet} containing collected user-agent.
	 */
	public Set getDevices() {
		return UnmodifiableSet.decorate(new HashSet(data.values()));
	}

	/**
	 * Return a device by collected user-agent.
	 * 
	 * @param userAgent
	 *            The user-agent corresponding to the device tried.
	 * @return The device identifier collected corresponding given user-agent,
	 *         if the given user-agent is not collected it returns null.
	 */
	public String getDevice(String userAgent) {
		
		Validate.notEmpty(userAgent, "The userAgent is empty");
		
		return (String) data.get(userAgent);
	}

	/**
	 * Store device identifier with corresponding user-agent.
	 * 
	 * @param userAgent
	 *            The user-agent associated to device identifier.
	 * @param deviceId
	 *            The device identifier to store.
	 */
	public void putDevice(String userAgent, String deviceId) {
		
		Validate.notEmpty(userAgent, "The userAgent is empty");
		Validate.notEmpty(deviceId, "The deviceId is empty");
		
		data.put(userAgent, deviceId);
	}
	
	public boolean containsDevice(String deviceId) {
		
		Validate.notEmpty(deviceId, "The deviceId is empty");
		
		return data.values().contains(deviceId);
	}
	
	// Common methods *****************************************************

	public String toString() {
		return new ToStringBuilder(this).append(getDevices()).toString();
	}

}
